package com.ihrm.shiro.config;

import com.ihrm.shiro.realm.CustomRealm;
import com.ihrm.system.service.UserService;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @auther chongxiongwei
 * @create 2020-06-10-0:01
 */
@Configuration
public class ShiroConfig {

    @Bean
    public UserService userService(){
        return new UserService();
    }

    @Bean
    public CustomRealm realm(){
        return new CustomRealm();
    }

    // 配置创建安全管理器
    @Bean
    public SecurityManager securityManager(CustomRealm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(realm);
        return defaultWebSecurityManager;
    }

    // 配置创建shiro过滤器工厂
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/autherror?code=1");
        shiroFilterFactoryBean.setUnauthorizedUrl("/autherror?code=2");
        // 设置过滤器集合
        Map<String,String> map = new LinkedHashMap<>();
        map.put("/user/home","anon");
        map.put("/user/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    // 开启shiro注解支持
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
